package com.taskflow.service;

import com.taskflow.entity.DownloadTask;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 任务调度Service
 */
@Slf4j
@Service
public class TaskSchedulerService {

    @Autowired
    private Scheduler scheduler;

    /**
     * 添加定时任务
     */
    public void scheduleTask(DownloadTask task) {
        try {
            JobKey jobKey = JobKey.jobKey("task_" + task.getId(), "download_group");
            
            // 如果任务已存在，先删除
            if (scheduler.checkExists(jobKey)) {
                scheduler.deleteJob(jobKey);
            }
            
            // 创建JobDetail
            JobDetail jobDetail = JobBuilder.newJob(DownloadJob.class)
                    .withIdentity(jobKey)
                    .usingJobData("taskId", task.getId())
                    .build();
            
            // 创建Trigger
            CronTrigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity("trigger_" + task.getId(), "download_group")
                    .withSchedule(CronScheduleBuilder.cronSchedule(task.getCronExpression()))
                    .build();
            
            // 调度任务
            scheduler.scheduleJob(jobDetail, trigger);
            log.info("定时任务已添加: taskId={}, cron={}", task.getId(), task.getCronExpression());
        } catch (Exception e) {
            log.error("添加定时任务失败: taskId={}", task.getId(), e);
            throw new RuntimeException("添加定时任务失败: " + e.getMessage());
        }
    }

    /**
     * 删除定时任务
     */
    public void removeTask(Long taskId) {
        try {
            JobKey jobKey = JobKey.jobKey("task_" + taskId, "download_group");
            if (scheduler.checkExists(jobKey)) {
                scheduler.deleteJob(jobKey);
                log.info("定时任务已删除: taskId={}", taskId);
            }
        } catch (Exception e) {
            log.error("删除定时任务失败: taskId={}", taskId, e);
        }
    }

    /**
     * 手动执行任务
     */
    public void executeTask(Long taskId) {
        try {
            JobKey jobKey = JobKey.jobKey("task_" + taskId, "download_group");
            if (scheduler.checkExists(jobKey)) {
                scheduler.triggerJob(jobKey);
                log.info("手动触发任务执行: taskId={}", taskId);
            } else {
                throw new RuntimeException("任务不存在或未启用");
            }
        } catch (Exception e) {
            log.error("手动执行任务失败: taskId={}", taskId, e);
            throw new RuntimeException("手动执行任务失败: " + e.getMessage());
        }
    }
}

